package com.cbtx.tablet.ui

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import com.cbtx.tablet.App
import com.cbtx.tablet.R
import com.cbtx.tablet.adapter.PagerAdapter
import com.cbtx.tablet.bean.ChangeAdvEvent
import com.cbtx.tablet.bean.Report
import com.cbtx.tablet.bean.ScreenSaverBean
import com.cbtx.tablet.bean.TabEntity
import com.cbtx.tablet.constant.HttpConstant
import com.cbtx.tablet.constant.HttpConstant.DEVICE_WXQRCODE
import com.cbtx.tablet.dialog.QRCodeDialog
import com.cbtx.tablet.exception.RequestException
import com.cbtx.tablet.fragments.GoodsFragment
import com.cbtx.tablet.fragments.GoodsTreasureFragment
import com.cbtx.tablet.fragments.VrFragment
import com.cbtx.tablet.net.HttpResponse
import com.cbtx.tablet.service.FloatVideoWindowService
import com.cbtx.tablet.service.TaskService
import com.cbtx.utils.DeviceUtil
import com.cbtx.utils.FileUtil
import com.cbtx.utils.InstallApkUtil
import com.cbtx.utils.zxing.ZxingUtils
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadSampleListener
import com.liulishuo.filedownloader.FileDownloader
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.util.concurrent.TimeUnit


class MainActivity : AbsBaseActivity() {

    companion object {
        const val TAG = "MainActivity"
        const val DEFAULT_REPORT_POLL_TIME = 20000L
        val advBannerList = mutableListOf<ScreenSaverBean>()
    }

    private var defaultPollReportTime = DEFAULT_REPORT_POLL_TIME
    private var defaultPollUpgradeTime = DEFAULT_REPORT_POLL_TIME * 15

    private val fragmentList: MutableList<Fragment> = ArrayList()
    private val mTabEntities = ArrayList<CustomTabEntity>()

    private var reportDispose: Disposable? = null
    private var upgradeDispose: Disposable? = null

    private var topClickTime: Long = 0
    private var topClickCount = 0

    private var isAlreadyBind = false

    private val mIconUnselectIds = intArrayOf(
        R.mipmap.sp_tab_renzheng_normal,
        R.mipmap.sp_tab_goods_normal,
        R.mipmap.sp_tab_vr_normal,
        R.mipmap.sp_tab_qrcode_normal
    )
    private val mIconSelectIds = intArrayOf(
        R.mipmap.sp_tab_renzheng_focus,
        R.mipmap.sp_tab_goods_focus,
        R.mipmap.sp_tab_vr_focus,
        R.mipmap.sp_tab_qrcode_focus
    )

    lateinit var baseFragmentPagerAdapter: PagerAdapter
    private var lastPosition = 0

    override fun layoutId(): Int = R.layout.activity_main

    override fun initView(savedInstanceState: Bundle?) {
        iv_touch.setOnTouchListener { _, _ ->
            TaskService.activityTouchTime = System.currentTimeMillis()
            return@setOnTouchListener false
        }

        iv_to_system_set.setOnClickListener {
            val time2 = System.currentTimeMillis() - topClickTime
            if (time2 > 1500) {
                topClickCount = 1
            } else {
                topClickCount++
            }
            if (topClickCount >= 10) {
                val localIntent = Intent(Settings.ACTION_SETTINGS)
                startActivity(localIntent)
                topClickCount = 0
            }
            topClickTime = System.currentTimeMillis()
        }

        ivUnbind.setOnLongClickListener {
            startActivity(Intent(this@MainActivity, DeviceInfoActivity::class.java))
            return@setOnLongClickListener false
        }

        for (i in 0..3) {
            mTabEntities.add(TabEntity(null, mIconSelectIds[i], mIconUnselectIds[i]))
        }
        fragmentList.add(GoodsFragment())
        fragmentList.add(GoodsTreasureFragment())
        fragmentList.add(VrFragment())

        baseFragmentPagerAdapter = PagerAdapter(supportFragmentManager, fragmentList)
        mViewPager.adapter = baseFragmentPagerAdapter

        initTableLayout()

        reportDispose = Observable.interval(0, 10, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                report()
            }

        upgradeDispose = Observable.interval(0, defaultPollUpgradeTime, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                checkVersion()
            }

        // 管理banner的service
        val serviceIntent = Intent(this, TaskService::class.java)
        startService(serviceIntent)
    }

    override fun initData(savedInstanceState: Bundle?) {
        getStoreInfo()
        showMiniWidow()
    }

    override fun reportSuccess(obj: HttpResponse<Report>?) {
        if (obj?.data != null) {
            if (obj.data?.newChange?.isNewUpgrade()!!) {
                Log.e("TAG", "newUpgrade")
                checkVersion()
            }
        }

        when (obj?.code) {
            RequestException.CODE_PERMISSION_DENIED,
            RequestException.CODE_DEVICE_DID_NOT_REGISTER,
            RequestException.CODE_DEVICE_TOKEN_INVALID,
            RequestException.CODE_DEVICE_IS_FROZEN,
            RequestException.CODE_COMPANY_OUT_OF_SERVICE -> {
                SPUtils.getInstance().put("isBind", false)
                //获取数据后，允许进入首页
                reportDispose?.apply {
                    if (!this.isDisposed) {
                        this.dispose()
                    }
                }
                startActivity(Intent(this@MainActivity, StartActivity::class.java))
                finish()
            }

            else -> {

                SPUtils.getInstance().put("isBind", true)

                if (defaultPollReportTime != obj?.data?.pollConfig?.get(0)?.pollIntervalTime?.toLong()) {
                    defaultPollReportTime = obj?.data?.pollConfig?.get(0)?.pollIntervalTime?.toLong()!!
                    reportDispose?.apply {
                        if (!this.isDisposed) {
                            this.dispose()
                        }
                    }
                    reportDispose =
                        Observable.interval(defaultPollReportTime, defaultPollReportTime, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                report()
                            }
                }

                if (defaultPollUpgradeTime != obj.data?.pollConfig?.get(3)?.pollIntervalTime?.toLong()) {
                    defaultPollUpgradeTime = obj.data?.pollConfig?.get(3)?.pollIntervalTime?.toLong()!!
                    upgradeDispose?.apply {
                        if (!this.isDisposed) {
                            this.dispose()
                        }
                    }
                    upgradeDispose =
                        Observable.interval(defaultPollUpgradeTime, defaultPollUpgradeTime, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                checkVersion()
                            }
                }
            }
        }
    }


    override fun onResume() {
        super.onResume()
        if (NetworkUtils.isConnected()) {
            tv_netTips.visibility = View.GONE
        } else {
            tv_netTips.visibility = View.VISIBLE
        }
    }

    override fun onRestart() {
        super.onRestart()
        TaskService.activityTouchTime = System.currentTimeMillis()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isAlreadyBind) {
            unbindService(mVideoCallServiceConnection)
        }
    }

    //检查广告
    private fun checkAdvBanner() {
        requestBanner()
        Handler().postDelayed({
            checkAdvBanner()
        }, 1000 * 60 * 10)
    }

    private fun requestBanner() {
        App.sApiServiceHolder.getApiService(HttpConstant.CONTENT_ALIAS)
            .getBanner(SPUtils.getInstance().getInt("storeId", 0))
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //请求失败重连次数
            .retry(2)
            .subscribeBy(
                onError = {
                    LogUtils.e(it.toString())
                },
                onNext = {

                    advBannerList.clear()

                    it?.data?.let { it1 ->
                        it1.forEachIndexed { index, screenSaverBean ->
                            if (screenSaverBean.fileType == "img") {
                                advBannerList.add(screenSaverBean)
                            } else {
                                var path = FileUtil.getDownloadDir() + screenSaverBean.filePath.toString()
                                    .substring(screenSaverBean.filePath.toString().lastIndexOf("/"))
                                var file = File(path)
                                if (!file.exists()) {
                                    FileDownloader.setup(this)
                                    FileDownloader.getImpl().create(screenSaverBean.filePath.toString())
                                        .setPath(path, false)
                                        .setListener(object : FileDownloadSampleListener() {
                                            override fun error(task: BaseDownloadTask, e: Throwable) {
                                                super.error(task, e)
                                                Log.e("TAG", "异常：$e")
                                            }

                                            override fun progress(
                                                task: BaseDownloadTask,
                                                soFarBytes: Int,
                                                totalBytes: Int
                                            ) {
                                                super.progress(task, soFarBytes, totalBytes)
                                                Log.e("TAG", "应用安装进度：$soFarBytes--$totalBytes")
                                            }

                                            override fun completed(task: BaseDownloadTask) {
                                                super.completed(task)
                                                // 下载完成
                                                screenSaverBean.filePath = path
                                                advBannerList.add(screenSaverBean)
                                                val changeAdvEvent = ChangeAdvEvent()
                                                changeAdvEvent.bannerItemList?.addAll(advBannerList)
                                                EventBus.getDefault().post(changeAdvEvent)
                                            }
                                        }).start()
                                } else {
                                    screenSaverBean.filePath = path
                                    advBannerList.add(screenSaverBean)
                                }
                            }
                        }
                    }
                }
            )
    }

    private fun initTableLayout() {
        tl_2.setTabData(mTabEntities)
        tl_2.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                if (position == fragmentList.size) {
                    val url = DEVICE_WXQRCODE + DeviceUtil.getSerialNumber(this@MainActivity)
                    val qRCodeDialog = ZxingUtils.createQRCode(
                        url,
                        340,
                        BitmapFactory.decodeResource(
                            resources,
                            R.mipmap.ic_logo_qr_code
                        )
                    )?.let {
                        QRCodeDialog(
                            this@MainActivity,
                            it
                        )
                    }
                    qRCodeDialog?.setOnDismissListener {
                        tl_2.currentTab = lastPosition
                    }
                    qRCodeDialog?.show()
                } else {
                    lastPosition = position
                    mViewPager.currentItem = position
                }
            }

            override fun onTabReselect(position: Int) {

            }
        })
        mViewPager.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                lastPosition = position
                tl_2.currentTab = position
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })

        mViewPager.currentItem = 0
    }

    /**
     * 悬浮菜单按钮
     */
    private val mVideoCallServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            isAlreadyBind = true
        }

        override fun onServiceDisconnected(name: ComponentName) {
            isAlreadyBind = false
        }
    }

    private fun getStoreInfo() {

        App.sApiServiceHolder.getApiService(HttpConstant.CONTENT_ALIAS)
            .getStoreInfo()
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //请求失败重连次数
            .retry(2)
            .subscribeBy(
                onError = {
                    LogUtils.e(it.toString())
                },
                onNext = {
                    SPUtils.getInstance().put("storeName", it.data?.storeName)
                    SPUtils.getInstance().put("roomCode", it.data?.roomCode)
                    SPUtils.getInstance().put("storeId", it.data?.storeId!!)
                    checkAdvBanner()
                }
            )
    }

    private fun showMiniWidow() {

        if (!isAlreadyBind) {
            val serviceVideoIntent = Intent(this@MainActivity, FloatVideoWindowService::class.java)
            isAlreadyBind =
                bindService(serviceVideoIntent, mVideoCallServiceConnection, Context.BIND_AUTO_CREATE) //绑定Service
        }
    }


    //检查版本
    private fun checkVersion() {

        var map = mutableMapOf<String, Any>()
        map["packageName"] = packageName(App.instance)

        App.sApiServiceHolder.getApiService(HttpConstant.CONTENT_ALIAS)
            .getUpgrade(map)
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //请求失败重连次数
            .retry(2)
            .subscribeBy(
                onError = {
                    LogUtils.e(it.toString())
                },
                onNext = {
                    if (it?.data != null && it.data?.size!! > 0) {
                        for (upgradeInfo in it.data!!) {
                            when (upgradeInfo.upgradeType?.toInt()) {
                                0 -> downloadApk(upgradeInfo.url!!)
                                else -> {
                                }
                            }
                        }
                    }
                }
            )
    }

    //这是要静默安装的
    private fun downloadApk(downloadUrl: String) {

        if (TextUtils.isEmpty(downloadUrl)) {
            return
        }
        val indext = downloadUrl.lastIndexOf("/") + 1
        val fileName = downloadUrl.substring(indext)
        val filePath = FileUtil.getDownloadDir()
        val allPath = "$filePath$fileName"

        FileDownloader.setup(this)
        FileDownloader.getImpl().create(downloadUrl)
            .setPath(filePath + fileName, false)
            .setListener(object : FileDownloadSampleListener() {
                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.pending(task, soFarBytes, totalBytes)
                    Log.d(TAG, "pending")
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.progress(task, soFarBytes, totalBytes)
                    Log.d(TAG, "progress")
                }

                override fun error(task: BaseDownloadTask, e: Throwable) {
                    super.error(task, e)
                    Log.d(TAG, "error")
                }

                override fun connected(
                    task: BaseDownloadTask,
                    etag: String,
                    isContinue: Boolean,
                    soFarBytes: Int,
                    totalBytes: Int
                ) {
                    super.connected(task, etag, isContinue, soFarBytes, totalBytes)
                    Log.d(TAG, "connected")
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.paused(task, soFarBytes, totalBytes)
                    Log.d(TAG, "paused")
                }

                override fun completed(task: BaseDownloadTask?) {
                    super.completed(task)
                    Handler().postDelayed({ //进入安装
                        if (checkIsCanGou("com.cbtx.app_manager")) {
                            val intent: Intent =
                                App.instance.packageManager.getLaunchIntentForPackage("com.cbtx.app_manager")!!
                            App.instance.startActivity(intent)
                        }
                        InstallApkUtil.installSilent(allPath)
                    }, 2000)
                }
            }).start()
    }

    private fun checkIsCanGou(launchItent: String): Boolean {
        return File("/data/data/$launchItent").exists()
    }

    @SuppressLint("RestrictedApi")
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        return if (event!!.keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else {
            super.dispatchKeyEvent(event)
        }
    }
}